package zhongbo.java.air.flightpath.listener;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import zhongbo.java.air.flightpath.dto.FlightPathDto;
import zhongbo.java.air.flightpath.mapper.FlightPathMapper;
import zhongbo.java.air.flightpath.model.FlightPath;
import zhongbo.java.air.flightpath.service.FlightPathService;

import java.io.IOException;


@Component
public class RedisSubChanelListener implements MessageListener {

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Autowired
    private FlightPathService flightPathService;

    /**
     * 接受广播消息
     * @param message
     * @param bytes
     */
    @Override
    public void onMessage(Message message, byte[] bytes) {
        String msg = redisTemplate.getStringSerializer().deserialize(message.getBody());

        ObjectMapper objectMapper = new ObjectMapper();
        try {
            FlightPathDto flightPathDto = objectMapper.readValue(objectMapper.readTree(msg).asText(), FlightPathDto.class);

            FlightPath flightPath = new FlightPath();
            flightPath.setId(flightPathDto.getId());
            flightPath.setLatitude(flightPathDto.getLatitude());
            flightPath.setLongitude(flightPathDto.getLongitude());
            flightPath.setTimestamp(flightPathDto.getTimestamp());
            flightPath.setHeading(flightPathDto.getHeading().intValue());
            flightPath.setSpeed(flightPathDto.getSpeed().intValue());
            flightPath.setAltitude(flightPathDto.getAltitude().intValue());
            flightPath.setSourceType(flightPathDto.getSourceType());
            flightPath.setIcaoCode(flightPathDto.getIcaoCode());
            flightPathService.saveAirCraft(flightPath);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        System.out.println("广播消息内容：" + msg);
    }
}
